package com.itheima.flinkmomo.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.util.Map;

public class HttpClientUtils {

    //传入经纬度, 返回查询的地区
    public static String findByLatAndLng(String lat , String lng){
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=YHZohhGR2xuRg36nufVjblu3mogqqGAN&output=json&coordtype=wgs84ll&location="+lat+","+lng;
            System.out.println(url);
            HttpGet httpGet = new HttpGet(url);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity httpEntity = response.getEntity();

            String json = EntityUtils.toString(httpEntity);

            Map<String,Object> result = JSONObject.parseObject(json, Map.class);
            if(result.get("status").equals(0)){
                Map<String,Object> resultMap =  (Map<String,Object>)result.get("result");
                resultMap = (Map<String, Object>) resultMap.get("addressComponent");
                String province = (String) resultMap.get("province");
                return province;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
